from flask import current_app
from flask import g, jsonify
from flask import request

from info.models import Order, House
from info.modules.index import api
from info.utils.common import user_login
from info.utils.response_code import RET


@api.route("/orders")
@user_login
def get_user_orders():
    """查询用户下的所有订单"""
    # 取到当前用户id
    user_id = g.user.id
    role = request.args.get("role")
    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    if role not in ("custom", "landlord"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        if "custom" == role:
            # 查询房客的订单:从订单列表中查询usert_id为当前登录用户的id
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        elif "landlord" == role:
            # 查询房东的订单：要先查询出房东所拥有的房屋id，在去订单表中查询指定的房屋id的订单
            houses = House.query.filter(House.user_id == user_id).all()
            # 获取到组件所有的房屋id
            houses_id = [house.id for house in houses]
            orders = Order.query.filter(Order.house_id.in_(houses_id)).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    orders_dict = [order.to_dict() for order in orders]

    return jsonify(errno=RET.OK, errmsg="ok", data={"orders": orders_dict})